package mysql

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"order_srv/appconfig"
	"sync"
)

var (
	DB   *gorm.DB
	err  error
	once sync.Once
)

func InitMysql() {
	//动态配置
	res := appconfig.AppData.MySQLConfig
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", res.Name, res.Pwd,
		res.Head, res.Pore, res.DBName)

	once.Do(func() {
		DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	})
	if err != nil {
		fmt.Println("数据库链接失败", err)
	}
	fmt.Println("数据库链接成功", res)
	//自动迁移
	DB.AutoMigrate(&Goods{}, Order{})
}
